﻿""" 壁球游戏
"""
import pygame
import sys

pygame.init()
size = width, height = 600, 400
speed = [1,1]
BLACK = 0, 0, 0

screen = pygame.display.set_mode(size)
pygame.display.set_caption("壁球游戏")

ball = pygame.image.load("PYG02-ball.gif") # 加载图片
ballrect = ball.get_rect() 

fps = 300 # 帧率
fclock = pygame.time.Clock() # 时钟

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN: # 响应方向键
            if event.key == pygame.K_LEFT:
                speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1)*int(speed[0]/abs(speed[0]))
            elif event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1
            elif event.key == pygame.K_UP:
                speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1
            elif event.key == pygame.K_DOWN:
                speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1)*int(speed[1]/abs(speed[1]))

    ballrect = ballrect.move(speed[0], speed[1]) # 移动
    if ballrect.left < 0 or ballrect.right > width: # 反弹
        speed[0] = - speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = - speed[1]

    screen.fill(BLACK) # 填充背景色
    screen.blit(ball, ballrect) # 在新位置重绘壁球
    pygame.display.update()
    
    fclock.tick(fps) # 控制刷新速度